<?php
/**
 * FastApp.
 * 9/14/24
 * @Author deepsea159
 * @Contact telegram:deepsea159
 */

namespace App\Game\Job;

use App\Fastapp\Model\AccountInviteLevel;
use App\Game\Api\Service\VipService;
use App\Game\Model\GameAccountVip;
use App\Game\Model\GameVip;
use Hyperf\AsyncQueue\Job;
use App\Marketing\Model\MarketingGradient;
use App\Marketing\Model\MarketingGradientLog;

class GradientJob extends Job
{
    public function __construct(public int $user_id, public int $data_id, public string $event, public int $account_type)
    {
    }

    public function handle(): void
    {
        if ($this->event == 'BetEvent') $this->upVipLevel();
        elseif ($this->event == 'AccountRechargeEvent') $this->recharge();
    }

    public function recharge(): void
    {
        $map = ['status' => 1, 'account_type' => $this->account_type];
        foreach (MarketingGradient::query()->where($map)->get() as $gradient) {
            if ($gradient->code == 'invite') {
                $this->invite($gradient);
            }
        }
    }

    public function upVipLevel(): void
    {
        $service = new VipService();
        $res = $service->level($this->user_id);
        /* @var GameVip $level */
        $level = $res['next'];
        if (!$level) return;
        if ($res['amount'] <= 0) {
            GameAccountVip::query()->where(['user_id' => $this->user_id])->update(['level' => $level->level, 'last_at' => date('Y-m-d H:i:s')]);
        }
    }

    public function invite(MarketingGradient $gradient): void
    {
        $parent_id = AccountInviteLevel::query()->where(['user_id' => $this->user_id])->value('parent_id');
        if (!$parent_id) return;
        $log = MarketingGradientLog::query()->where(['user_id' => $this->user_id, 'gradient_id' => $gradient->id])->orderByDesc('id')->first();
        $total = AccountInviteLevel::query()->where(['parent_id' => $parent_id, 'status' => 1])->count();

        foreach ($gradient->config as $idx => $item) {
            if ($item['amount'] <= $total && (!$log || $log->idx < $idx)) {
                MarketingGradientLog::query()->create([
                    'gradient_id' => $gradient->id,
                    'amount' => $item['amount'],
                    'refunded' => $item['refunded'],
                    'idx' => $idx,
                    'user_id' => $this->user_id,
                    'date' => date('Y-m-d'),
                ]);
            }
        }
    }
}